package com.example.demo.config;

import com.example.demo.common.ResultAjax;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//统一返回值的保底实现类
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;

    //true才会调用beforeBodyWrite方法
    //反之不会调用beforeBodyWrite方法
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //已经包装好的对象
        if(body instanceof ResultAjax){
            return body;
        }
        //对字符串进行判断和处理
        if(body instanceof String){
            ResultAjax resultAjax=ResultAjax.succ(body);
            try{
                return objectMapper.writeValueAsString(resultAjax);
            }catch (JsonProcessingException e){
                e.printStackTrace();
            }
        }
        return ResultAjax.succ(body);
    }
}
